//
//  FriendRequestViewController.m
//  WFChat UIKit
//
//  Created by WF Chat on 2017/10/7.
//  Copyright © 2017年 WildFireChat. All rights reserved.
//

#import "WFCUFriendRequestViewController.h"
#import <WFChatClient/WFCChatClient.h>
#import "WFCUProfileTableViewController.h"
#import <SDWebImage/SDWebImage.h>
#import "WFCUFriendRequestTableViewCell.h"
#import "MBProgressHUD.h"
#import "WFCUAddFriendViewController.h"
#import "UIView+Toast.h"
#import "WFCUConfigManager.h"

#import "UIView+Toast.h"
#import "YGExtendChain.h"
#import "AFNetworking.h"
#import "YGExtendChain.h"
#import "SDAutoLayout.h"


@interface WFCUFriendRequestViewController () <UITableViewDataSource, UITableViewDelegate, WFCUFriendRequestTableViewCellDelegate>
@property (nonatomic, strong)  UITableView              *tableView;
@property (nonatomic, strong) NSArray            *dataList;
@end

@implementation WFCUFriendRequestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSearchUIAndData];
  
    
    if (self.isGroup == 1) {
        [self getData];
      
    }else{
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoUpdated:) name:kUserInfoUpdated object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFriendRequestUpdated:) name:kFriendRequestUpdated object:nil];
        
        
        [[WFCCIMService sharedWFCIMService] clearUnreadFriendRequestStatus];

    }
    
}
- (void)getData{
    
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
//        NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

    if(authToken.length) {
        [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
 
    }
 
    
    WEAKSELF_ZM
    __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = WFCString(@"加载中...");
    [hud showAnimated:YES];

    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/group/applyList" ];
//    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
    [manager GET:url
       parameters:nil
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            hud.hidden = YES;

            NSDictionary *dic = responseObject;
            NSLog(@" ret---  %@ ", dic );
            
            if([[dic handleNullObjectForKey:@"code"] intValue] == 0) {
                
                NSMutableArray *datas = @[].mutableCopy;
                NSArray *list = [dic handleNullObjectForKey:@"result"];
                for (int i = 0; i<list.count; i++) {
                    NSDictionary *dic1 = list[i];

                    WFCCGroupRequest *model = [[WFCCGroupRequest alloc]init];
                    model.reason = [dic1 handleNullObjectForKey:@"reason"];
                    model.groupName = [dic1 handleNullObjectForKey:@"groupName"];
                    model.nickName = [dic1 handleNullObjectForKey:@"nickName"];
                    model.gid = [dic1 handleNullObjectForKey:@"gid"];
                    model.uid = [dic1 handleNullObjectForKey:@"uid"];
                    model.groupPortrait = [dic1 handleNullObjectForKey:@"groupPortrait"];
                    model.id = [dic1 handleNullObjectForKey:@"id"];
                    model.status = [[dic1 handleNullObjectForKey:@"status"] intValue];
                    model.timestamp = [[dic1 handleNullObjectForKey:@"dt"] longLongValue];
                    model.timestamp = [[dic1 handleNullObjectForKey:@"dt"] longLongValue];
                    model.portrait = [dic1 handleNullObjectForKey:@"portrait"];

                    

                    [datas addObject:model];
                }
                weakSelf.dataList = datas;
                [weakSelf.tableView reloadData];

            }
            
            
        });
 
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            
            NSLog(@" ret---  %@ ", error );
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.hidden = YES;

        });
        
    }];
    
}
- (void)onUserInfoUpdated:(NSNotification *)notification {
    NSArray<WFCCUserInfo *> *userInfoList = notification.userInfo[@"userInfoList"];
    for (int i = 0; i < self.dataList.count; ++i) {
        WFCCFriendRequest *request = self.dataList[i];
        for (WFCCUserInfo *userInfo in userInfoList) {
            if([userInfo.userId isEqualToString:request.target]) {
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            }
        }
    }
}

- (void)onFriendRequestUpdated:(NSNotification *)notification {
    self.dataList   = [[WFCCIMService sharedWFCIMService] getIncommingFriendRequest];
    [self.tableView reloadData];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.isGroup == 0) {
        [[WFCCIMService sharedWFCIMService] clearUnreadFriendRequestStatus];
    }
}

- (void)initSearchUIAndData {
    self.view.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
    
    if (self.isGroup == 0) {
        self.navigationItem.title = WFCString(@"NewFriend");

        
        //初始化数据源
        [[WFCCIMService sharedWFCIMService] loadFriendRequestFromRemote];
        _dataList   = [[WFCCIMService sharedWFCIMService] getIncommingFriendRequest];

        
        self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc] initWithTitle:WFCString(@"Clear") style:UIBarButtonItemStyleDone target:self action:@selector(onClearBarBtn:)], [[UIBarButtonItem alloc] initWithTitle:WFCString(@"添加朋友") style:UIBarButtonItemStyleDone target:self action:@selector(onAddBarBtn:)]];
        
        self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc] initWithTitle:WFCString(@"Clear") style:UIBarButtonItemStyleDone target:self action:@selector(onClearBarBtn:)]];
    }else{
        self.navigationItem.title = WFCString(@"群通知");
        ZmSaveUserDefaults(@(0), @"joinGroupCount");


    }
    
    CGFloat screenWidth = self.view.frame.size.width;
    CGFloat screenHeight = self.view.frame.size.height;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    
    //设置代理
    _tableView.delegate   = self;
    _tableView.dataSource = self;
    _tableView.allowsSelection = YES;
    _tableView.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    [self.view addSubview:_tableView];
  
    

    
}

- (void)onAddBarBtn:(UIBarButtonItem *)sender {
    UIViewController *addFriendVC = [[WFCUAddFriendViewController alloc] init];
    addFriendVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:addFriendVC animated:YES];
}

- (void)onClearBarBtn:(UIBarButtonItem *)sender {
    [[WFCCIMService sharedWFCIMService] clearFriendRequest:1 beforeTime:0];
    _dataList   = [[WFCCIMService sharedWFCIMService] getIncommingFriendRequest];
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - UITableViewDataSource

//table 返回的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
      return [self.dataList count];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
//返回单元格内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *requestFlag = @"request_cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:requestFlag];
  
  if (cell == nil) {
    cell = [[WFCUFriendRequestTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:requestFlag];
  }
  
  
  WFCUFriendRequestTableViewCell *frCell = (WFCUFriendRequestTableViewCell *)cell;
  frCell.delegate = self;
    if (self.isGroup == 1) {
        WFCCGroupRequest *request = self.dataList[indexPath.row];
        frCell.groupRequest = request;

        
    } else {
        WFCCFriendRequest *request = self.dataList[indexPath.row];
        frCell.friendRequest = request;

    }
 
  cell.userInteractionEnabled = YES;
  return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isGroup == 1) {
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (self.isGroup == 1) {
            
        }else{
            WFCCFriendRequest *request = self.dataList[indexPath.row];
            [[WFCCIMService sharedWFCIMService] deleteFriendRequest:request.target direction:request.direction];
            _dataList   = [[WFCCIMService sharedWFCIMService] getIncommingFriendRequest];
            [self.tableView reloadData];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64;///<.统一行高>
}
#pragma mark - FriendRequestTableViewCellDelegate
- (void)onAcceptGroupRequest:(WFCCGroupRequest *)groupRequest{
 
    WEAKSELF_ZM
    __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = WFCString(@"加载中。。。");
    [hud showAnimated:YES];
 
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

    if(authToken.length) {
        [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
 
    }
 
    
     
    NSDictionary *parameters = @{@"gid":groupRequest.gid,@"uid":groupRequest.uid,@"status":@(1)}; ///<.TEXT, IMAGE, VIDEO
 
    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/group/dealApply" ];
//    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
    [manager POST:url
       parameters:parameters
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            

            NSDictionary *dic = responseObject;
            NSLog(@" ret---  %@ ", dic );
            
            if([[dic handleNullObjectForKey:@"code"] intValue] == 0) {
                hud.hidden = YES;
                
//                [[WFCCIMService sharedWFCIMService] addMembers:@[groupRequest.uid] toGroup:groupRequest.gid memberExtra:nil notifyLines:@[@(0)] notifyContent:nil success:^{
                    
                    [[WFCCIMService sharedWFCIMService] getGroupMembers:groupRequest.gid forceUpdate:YES];
                    [weakSelf.view makeToast:WFCString(@"成功")
                                    duration:2
                                    position:CSToastPositionCenter];
                    
                    [weakSelf getData];
                    
//                } error:^(int error_code) {
//                    
//                    if (error_code == ERROR_CODE_GROUP_EXCEED_MAX_MEMBER_COUNT) {
//                        [weakSelf.view makeToast:WFCString(@"ExceedGroupMaxMemberCount") duration:1 position:CSToastPositionCenter];
//                    } else {
//                        [weakSelf.view makeToast:WFCString(@"NetworkError") duration:1 position:CSToastPositionCenter];
//                    }
//                    
//                }];
                
 
                
            }else{
                
                hud.hidden = YES;
                [weakSelf.view makeToast:WFCString([dic handleNullObjectForKey:@"message"]) duration:1 position:CSToastPositionCenter];
              
            }
            
            
        });
 
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            
            NSLog(@" ret---  %@ ", error );
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.hidden = YES;

        });
        
    }];
    
}

- (void)onAcceptBtn:(NSString *)targetUserId {
    __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = WFCString(@"Updating");
    [hud showAnimated:YES];
    
    __weak typeof(self) ws = self;
    [[WFCCIMService sharedWFCIMService] handleFriendRequest:targetUserId accept:YES extra:nil success:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.hidden = YES;
            [ws.view makeToast:WFCString(@"UpdateDone")
                      duration:2
                      position:CSToastPositionCenter];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [[WFCCIMService sharedWFCIMService] loadFriendRequestFromRemote];
                dispatch_async(dispatch_get_main_queue(), ^{
                    ws.dataList   = [[WFCCIMService sharedWFCIMService] getIncommingFriendRequest];
                    for (WFCCFriendRequest *request in ws.dataList) {
                        if ([request.target isEqualToString:targetUserId]) {
                            request.status = 1;
                            break;
                        }
                    }
                    [ws.tableView reloadData];
                });
            });
        });
    } error:^(int error_code) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.hidden = YES;
            if(error_code == 19) {
                [ws.view makeToast:WFCString(@"Expired")
                          duration:2
                          position:CSToastPositionCenter];
            } else {
                [ws.view makeToast:WFCString(@"UpdateFailure")
                          duration:2
                          position:CSToastPositionCenter];
            }
        });
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _tableView        = nil;
    _dataList         = nil;
}
@end
